//! # 监控模块
//!
//! 重新导出 rustcloud-observability 模块的监控功能，
//! 为 rustcloud-stream 提供统一的监控能力。
//! 
//! 通过这种方式保持向后兼容性，同时使用公共功能模块。

// 重新导出 rustcloud-observability 的监控功能
pub use rustcloud_observability::monitoring::*;

// 为流处理定制的监控实现
use async_trait::async_trait;
use std::time::Duration;
use crate::core::{StreamMessage, StreamResult};

/// 流处理专用监控器
pub struct StreamMonitor {
    /// 底层监控器
    inner: Box<dyn rustcloud_observability::monitoring::Monitor>,
    /// 流处理标识符
    stream_id: String,
}

impl StreamMonitor {
    /// 创建新的流监控器
    pub fn new(
        inner: Box<dyn rustcloud_observability::monitoring::Monitor>,
        stream_id: String,
    ) -> Self {
        Self { inner, stream_id }
    }

    /// 记录流消息处理
    pub async fn record_stream_processed(
        &self,
        stream_name: &str,
        success: bool,
        duration: Duration,
    ) {
        let topic = format!("stream.{}.{}", self.stream_id, stream_name);
        self.inner.record_message_processed(&topic, success, duration).await;
    }

    /// 记录流消息发布
    pub async fn record_stream_published(&self, stream_name: &str, duration: Duration) {
        let topic = format!("stream.{}.{}", self.stream_id, stream_name);
        self.inner.record_message_published(&topic, duration).await;
    }

    /// 记录流处理错误
    pub async fn record_stream_error(
        &self,
        error_type: &str,
        error: &crate::error::StreamError,
    ) {
        let stream_error = rustcloud_observability::monitoring::MonitoringError::new(
            error.to_string(),
            None,
        );
        self.inner.record_error(error_type, &stream_error).await;
    }

    /// 获取流处理指标
    pub async fn get_stream_metrics(&self) -> StreamResult<StreamMonitoringMetrics> {
        let metrics = self.inner.get_metrics().await
            .map_err(|e| crate::error::StreamError::Monitoring(e.to_string()))?;

        Ok(StreamMonitoringMetrics {
            stream_id: self.stream_id.clone(),
            throughput: metrics.throughput,
            latency: metrics.latency,
            error_rate: metrics.error_rate,
            resource_usage: metrics.resource_usage,
            collected_at: metrics.collected_at,
        })
    }
}

#[async_trait]
impl rustcloud_observability::monitoring::Monitor for StreamMonitor {
    async fn record_message_published(&self, topic: &str, duration: Duration) {
        self.inner.record_message_published(topic, duration).await;
    }

    async fn record_message_processed(&self, topic: &str, success: bool, duration: Duration) {
        self.inner.record_message_processed(topic, success, duration).await;
    }

    async fn record_error(
        &self,
        error_type: &str,
        error: &rustcloud_observability::monitoring::MonitoringError,
    ) {
        self.inner.record_error(error_type, error).await;
    }

    async fn get_metrics(&self) -> rustcloud_observability::monitoring::Result<
        rustcloud_observability::monitoring::MonitoringMetrics
    > {
        self.inner.get_metrics().await
    }

    async fn health_check(&self) -> rustcloud_observability::monitoring::Result<
        rustcloud_observability::monitoring::HealthCheckResult
    > {
        self.inner.health_check().await
    }

    async fn get_metrics_history(
        &self,
        duration: Duration,
    ) -> rustcloud_observability::monitoring::Result<
        Vec<rustcloud_observability::monitoring::MonitoringMetrics>
    > {
        self.inner.get_metrics_history(duration).await
    }
}

/// 流监控指标
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct StreamMonitoringMetrics {
    /// 流处理标识符
    pub stream_id: String,
    /// 吞吐量指标
    pub throughput: rustcloud_observability::monitoring::ThroughputMetrics,
    /// 延迟指标
    pub latency: rustcloud_observability::monitoring::LatencyMetrics,
    /// 错误率指标
    pub error_rate: rustcloud_observability::monitoring::ErrorRateMetrics,
    /// 资源使用指标
    pub resource_usage: rustcloud_observability::monitoring::ResourceUsageMetrics,
    /// 收集时间
    pub collected_at: chrono::DateTime<chrono::Utc>,
}

/// 流监控配置
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct StreamMonitoringConfig {
    /// 是否启用监控
    pub enabled: bool,
    /// 指标收集间隔（秒）
    pub collection_interval_secs: u64,
    /// 健康检查间隔（秒）
    pub health_check_interval_secs: u64,
    /// 指标保留时间（小时）
    pub metrics_retention_hours: u64,
    /// 延迟样本大小
    pub latency_sample_size: usize,
    /// 流处理标识符
    pub stream_id: String,
}

impl Default for StreamMonitoringConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            collection_interval_secs: 30,
            health_check_interval_secs: 60,
            metrics_retention_hours: 24,
            latency_sample_size: 1000,
            stream_id: "default-stream".to_string(),
        }
    }
}

/// 流健康检查器
pub struct StreamHealthChecker {
    /// 流处理标识符
    stream_id: String,
    /// 监控器引用
    monitor: std::sync::Weak<StreamMonitor>,
}

impl StreamHealthChecker {
    /// 创建新的流健康检查器
    pub fn new(stream_id: String, monitor: std::sync::Weak<StreamMonitor>) -> Self {
        Self { stream_id, monitor }
    }
}

#[async_trait]
impl rustcloud_observability::health::HealthChecker for StreamHealthChecker {
    async fn check_health(&self) -> rustcloud_observability::health::ComponentHealth {
        if let Some(monitor) = self.monitor.upgrade() {
            // 检查流监控器健康状态
            match monitor.health_check().await {
                Ok(result) => rustcloud_observability::health::ComponentHealth {
                    status: match result.status {
                        rustcloud_observability::monitoring::HealthStatus::Healthy => {
                            rustcloud_observability::health::HealthStatus::Healthy
                        }
                        rustcloud_observability::monitoring::HealthStatus::Warning => {
                            rustcloud_observability::health::HealthStatus::Warning
                        }
                        rustcloud_observability::monitoring::HealthStatus::Critical => {
                            rustcloud_observability::health::HealthStatus::Critical
                        }
                    },
                    message: format!("流 {} 健康状态正常", self.stream_id),
                    details: std::collections::HashMap::new(),
                    last_check: chrono::Utc::now(),
                },
                Err(_) => rustcloud_observability::health::ComponentHealth {
                    status: rustcloud_observability::health::HealthStatus::Critical,
                    message: format!("流 {} 健康检查失败", self.stream_id),
                    details: std::collections::HashMap::new(),
                    last_check: chrono::Utc::now(),
                },
            }
        } else {
            rustcloud_observability::health::ComponentHealth {
                status: rustcloud_observability::health::HealthStatus::Critical,
                message: format!("流 {} 监控器已断开连接", self.stream_id),
                details: std::collections::HashMap::new(),
                last_check: chrono::Utc::now(),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_stream_monitoring_config_default() {
        let config = StreamMonitoringConfig::default();
        assert!(config.enabled);
        assert_eq!(config.collection_interval_secs, 30);
        assert_eq!(config.health_check_interval_secs, 60);
        assert_eq!(config.metrics_retention_hours, 24);
        assert_eq!(config.latency_sample_size, 1000);
        assert_eq!(config.stream_id, "default-stream");
    }

    #[test]
    fn test_stream_monitoring_metrics_serialization() {
        use rustcloud_observability::monitoring::*;
        
        let metrics = StreamMonitoringMetrics {
            stream_id: "test-stream".to_string(),
            throughput: ThroughputMetrics {
                messages_per_second: 100.0,
                messages_per_minute: 6000.0,
                total_messages: 1000,
                successful_messages: 950,
                failed_messages: 50,
            },
            latency: LatencyMetrics {
                average_ms: 10.5,
                p50_ms: 8.0,
                p95_ms: 20.0,
                p99_ms: 50.0,
                max_ms: 100.0,
            },
            error_rate: ErrorRateMetrics {
                error_percentage: 5.0,
                total_errors: 50,
                error_types: std::collections::HashMap::new(),
            },
            resource_usage: ResourceUsageMetrics {
                cpu_usage_percent: 25.5,
                memory_usage_mb: 128.0,
                active_connections: 10,
                queue_length: 0,
            },
            collected_at: chrono::Utc::now(),
        };

        let json = serde_json::to_string(&metrics).unwrap();
        let deserialized: StreamMonitoringMetrics = serde_json::from_str(&json).unwrap();
        
        assert_eq!(deserialized.stream_id, "test-stream");
        assert_eq!(deserialized.throughput.messages_per_second, 100.0);
    }
}